package com.blate.dogxiao.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.blate.dogxiao.activity.CitySelectorActivity;
import com.blate.dogxiao.activity.HouseDetailActivity;
import com.blate.dogxiao.adapter.HomeHouseAdapter;
import com.blate.dogxiao.adapter.SimpleDataRecyclerViewAdapter;
import com.blate.dogxiao.bean.HouseBean;
import com.blate.dogxiao.databinding.FragmentHomeBinding;
import com.blate.dogxiao.databinding.ItemHomeHouseBinding;
import com.blate.dogxiao.decoration.EquallySpacedDecoration;
import com.blate.dogxiao.function.AutoIoScheduler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * @author Blate
 * Created in 2021/4/20
 */
public class HomeFragment
        extends Fragment {

    private FragmentHomeBinding mBinding;

    private HomeHouseAdapter mHouseAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = FragmentHomeBinding.inflate(inflater, container, false);
        mBinding.setHost(this);
        initialize(inflater.getContext());
        return mBinding.getRoot();
    }

    private void initialize(Context context) {
        mBinding.rvHouse.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mBinding.rvHouse.addItemDecoration(new EquallySpacedDecoration(context, 4.5f));
        mHouseAdapter = new HomeHouseAdapter();
        mHouseAdapter.setItemChildClickListener(
                new SimpleDataRecyclerViewAdapter.MonitorViewCollector<ItemHomeHouseBinding>() {
                    @Override
                    public void collectorMonitorView(SimpleDataRecyclerViewAdapter.ItemViewMonitor itemViewMonitor, ItemHomeHouseBinding binding) {
                        itemViewMonitor.monitorView(binding.getRoot());
                    }
                },
                new SimpleDataRecyclerViewAdapter.OnItemChildClickListener<ItemHomeHouseBinding, HouseBean>() {
                    @Override
                    public void onItemChildClick(ItemHomeHouseBinding binding, View view, HouseBean data) {
                        Intent intent = new Intent(getContext(), HouseDetailActivity.class);
                        intent.putExtra(HouseDetailActivity.KEY_HOUSE_BEAN, data);
                        startActivity(intent);
                    }
                }
        );
        mBinding.rvHouse.setAdapter(mHouseAdapter);

        loadHouseData(context);
    }

    public void launchCitySelector() {
        startActivityForResult(new Intent(getContext(), CitySelectorActivity.class), 1001);
    }

    private void loadHouseData(Context context) {
        Observable.fromCallable(new Callable<List<HouseBean>>() {
            @Override
            public List<HouseBean> call() throws Exception {
                AssetManager assetManager = context.getAssets();
                try (InputStream inputStream = assetManager.open("house_data.json")) {
                    Type stringList = new TypeToken<ArrayList<HouseBean>>() {
                    }.getType();
                    return new Gson().fromJson(new InputStreamReader(inputStream), stringList);
                }
            }
        })
                .compose(new AutoIoScheduler<>())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(new Consumer<List<HouseBean>>() {
                    @Override
                    public void accept(List<HouseBean> houseBeans) throws Exception {
                        mHouseAdapter.putData(true, houseBeans);
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == AppCompatActivity.RESULT_OK) {
            if (requestCode == 1001) {
                if (data != null) {
                    mBinding.btCity.setText(data.getStringExtra("city"));
                }
            }
        }
    }
}
